package net.sf.nlp.segment;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;

public class TrieTreeNode 
{
	Map<String, TrieTreeNode> trieDict = new LinkedHashMap<String, TrieTreeNode>();
	
	List<WordItem> wordItems = null;
	
	boolean customized = false;
	
	public TrieTreeNode()
	{
		this(false);
	}
	
	public TrieTreeNode(boolean customized)
	{
		this.customized = customized;
	}
	
	public List<WordItem> getWordItems() {
		return wordItems;
	}

	public boolean isCustomized() {
		return customized;
	}

	public Map<String, TrieTreeNode> getTrieDict() {
		return trieDict;
	}

	public TrieTreeNode getChildByKey(String key)
	{
		return getChildByKey(key, false, false);
	}
	
	public TrieTreeNode getChildByKey(String key, boolean create, boolean customized)
	{
		TrieTreeNode node = trieDict.get(key);
		
		if (create && node == null)
		{
			node = new TrieTreeNode(customized);
			
			trieDict.put(key, node);
		}
		
		return node;
	}
	
	public void addChild(String words, long handle, long freq, boolean customized)
	{
		if (words == null || words.length() == 0)
		{
			if (wordItems == null)
				wordItems = new ArrayList<WordItem>();
			
			wordItems.add(new WordItem(handle, freq));
		}
		else
		{
			String key = words.substring(0, 1);
			String subString = null;
			
			if (words.length() > 1)
				subString = words.substring(1);
			
			TrieTreeNode node = getChildByKey(key, true, subString == null ? customized : false);
			node.addChild(subString, handle, freq, customized);
		}
	}
	
	public void clear()
	{
		trieDict.clear();
	}
	
	public void save(String file)
	{
		try 
		{
			BufferedWriter writer = new BufferedWriter(new FileWriter(new File(file)));
			
			save(this, "", writer);
			
			writer.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		
	}
	
	private void save(TrieTreeNode trieNode, String word, BufferedWriter writer) throws IOException
	{
		if (trieNode.getWordItems() != null)
		{
			for (WordItem wordItem : trieNode.getWordItems())
			{
				writer.write(word + " " + wordItem.getHandle() + " " + wordItem.getFreq());
				writer.write("\r\n");
			}
		}
		
		Map<String, TrieTreeNode> trieDict = trieNode.getTrieDict();
		
		Set<String> keys = trieDict.keySet();
		for (String key : keys)
			save(trieDict.get(key), word + key, writer);
		
		
		writer.flush();
	}
}
